package com.pxmeta.common.utils.wechat;

import com.alibaba.fastjson.JSONObject;
import com.pxmeta.common.exception.ServiceException;
import com.pxmeta.common.utils.AesUtil;
import lombok.SneakyThrows;
import lombok.extern.slf4j.Slf4j;
import java.nio.charset.StandardCharsets;
import java.security.GeneralSecurityException;

@Slf4j
public class WxPayCallbackUtil {

    /**
     * 对称解密
     */
    @SneakyThrows
    public static String decryptFromResource(JSONObject bodyMap, String apiV3Key) {
        // 通知数据
        JSONObject resourceMap = bodyMap.getJSONObject("resource");
        // 数据密文
        String ciphertext = resourceMap.getString("ciphertext");
        // 随机串
        String nonce = resourceMap.getString("nonce");
        // 附加数据
        String associateData = resourceMap.getString("associated_data");
        AesUtil aesUtil = new AesUtil(apiV3Key.getBytes(StandardCharsets.UTF_8));
        try {
            return aesUtil.decryptToString(associateData.getBytes(StandardCharsets.UTF_8), nonce.getBytes(StandardCharsets.UTF_8), ciphertext);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
            throw new ServiceException("解密失败");
        }
    }
}
